package jk.zmn.server.core;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

import org.omg.IOP.Codec;

import jk.zmn.server.utils.CODE;
import jk.zmn.server.utils.CloseUtils;

/**
 * @author zmn
 * 封装响应信息
 *
 */
public class Response {
	

	//定义响应中的换行
	private static final String CRLF="\r\n";
	//定义响应中的空格
	private static final String BLANK=" ";
	//头信息
	private StringBuilder headInfo;
	//正文信息
	private StringBuilder context;
	
	private BufferedWriter bufferedOutputStream;
	
	//正文字节长度
	//private int len;
	
	public Response() {
		headInfo = new StringBuilder();
		context = new StringBuilder();
	}
	
	Response(OutputStream outputStream){
		this();
		try {
			//this.bufferedOutputStream = new BufferedOutputStream(outputStream);
			 bufferedOutputStream = new BufferedWriter(new OutputStreamWriter(outputStream));
		} catch (Exception e) {
			headInfo = null;
		}
	}
	
	
	/**
	 * 添加正文
	 * @param info
	 */
	public void print(String info) {
		context.append(info);
	}
	
	public void println(String info) {
		context.append(info);
	}
	
	/**
	 * 创建头信息
	 */
	private void createHeadInfo(int code) {
		//封装http协议版本，响应码，
		headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK);
		switch (code) {
		case 200:
			headInfo.append("OK");
			break;
		case 404:
			headInfo.append("NOT FOUND");
			break;
		case 500:
			headInfo.append("SERVER ERROR");
			break;
		}
		headInfo.append(CRLF);
		//封装服务器版本
		headInfo.append("Server:jkzmn Server/1.0.0").append(CRLF);
		//封装返回数据格式和编码
		headInfo.append("Content-type:text/html;charset=utf8").append(CRLF);
		//返回响应时间
		headInfo.append("Date:"+new Date()).append(CRLF);
		//返回响应内容字节长度
		headInfo.append("Content-Length:"+context.toString().getBytes().length).append(CRLF);
		headInfo.append(CRLF);
	}
	
	//推送数据到客户端
	
	void pushToclient(int code) {
		//根据外界传入的响应码，构建不同的响应头
		if (headInfo==null) {
			code=500;
		}
		switch (code) {
		case 404:
			context = new StringBuilder();
			context.append(CODE.NOTFOUND.getValue());
			break;
		case 500:
			context = new StringBuilder();
			context.append(CODE.ERROR.getValue());
			break;
		}
		createHeadInfo(code);
		try {
			bufferedOutputStream.append(headInfo.toString());
			bufferedOutputStream.append(context.toString());
			bufferedOutputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	void close() {
		CloseUtils.closeIO(bufferedOutputStream);
	}
	
	
}
